import 'dart:async';

import 'package:demo/app/global.dart';
import 'package:demo/app/routes/app_pages.dart';
import 'package:demo/app/widgets/CommonDialog.dart';
import 'package:demo/utils/sp_util.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../model/login_model.dart';
import '../../../net/api_provider.dart';
import '../../../theme/app_text_theme.dart';
import '../main/home/home_controller.dart';

class LoginController extends GetxController{
  var platform =  const MethodChannel("sing.top/rth");

  var lastBackPressTime = -1;
  var phoneStr = '';
  var codeStr = '';
  var codeBtnStr = '获取验证码'.obs;
  var isAgree = false.obs; // 是否同意协议
  var canGetCode = true.obs; // 是否可以获取验证码

  void getCode() async {
    if(phoneStr.length != 11 || !phoneStr.startsWith('1')){
      EasyLoading.showToast('请输入正确的手机号');
    }else if(isAgree.isFalse){
      showAgreementDialog(() => getCode());
    }else{
      Map<String, dynamic> obj = {'phone': phoneStr,};
      //执行网络请求
      var result = await apiProvider.getData(obj,ApiProvider.login_code);
      if(result.code == 200){
        EasyLoading.showToast('验证码获取成功');
        startCountDown(60);
      }else{
        EasyLoading.showToast('验证码获取失败');
      }
    }
  }

  // 倒计时方法 time 倒计时时间
  void startCountDown(int time) {
    if(!canGetCode.value){
      return;
    }
    canGetCode.value = false;

    if (_timer != null) {
      killTimer();
    }
    if (time <= 0) {
      return;
    }

    var countTime = time;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countTime <= 0) {// 倒计时结束
        timer.cancel();
        codeBtnStr.value = '重新获取';
        canGetCode.value = true;
      } else {
        codeBtnStr.value = '${countTime}s';
        countTime--;
        canGetCode.value = false;
      }
    });
  }

  Timer? _timer; // 倒计时器
  void killTimer() {
    _timer?.cancel(); // 关闭计时器
    _timer = null; // 置空
  }

  @override
  void onInit() {
    super.onInit();

    SpUtil.write(SpUtil.TOKEN, '');
    SpUtil.write(SpUtil.PHONE, '');
    SpUtil.write(SpUtil.CHANNEL_ID, -1);
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    killTimer();
  }

  // 登录
  void login(){
    if(phoneStr.length != 11 || !phoneStr.startsWith('1')){
      EasyLoading.showToast('请输入正确的手机号');
    } else if (codeStr.isEmpty){
      EasyLoading.showToast('请输入验证码');
    } else if (isAgree.isFalse){
      showAgreementDialog(() => login());
    }else{
      requestLogin();
    }
  }

  ApiProvider apiProvider = Get.find();
  void requestLogin() async {
      Map<String, dynamic> obj = {
        'phone': phoneStr,
        'code': codeStr,
        'channel_code': Global.CHANNEL,
      };
    //执行网络请求
    var result = await apiProvider.getData(obj,ApiProvider.login);
    if(result.code == 200){
      var login = Login.fromJson(result.data);

      SpUtil.write(SpUtil.TOKEN, login.token);
      SpUtil.write(SpUtil.PHONE, login.phone);
      SpUtil.write(SpUtil.CHANNEL_ID, login.channel_id);

      Map<String, dynamic> jsonObject = {};
      jsonObject['token'] = login.token;
      jsonObject['phone'] = login.phone;
      jsonObject['channel_id'] = login.channel_id;
      platform.invokeMethod('setData', jsonObject);
      Get.offAllNamed(Routes.MAIN);
    }else{// 请求出错时
      EasyLoading.showToast('${result.msg}');
    }
  }

  void showAgreementDialog(Function fun){
    Get.dialog(
      CommonDialog(
        contentWidget: getContent(),
        yesStr: '同意',
        noStr: '取消',
        yesFun: ()=>{
          isAgree.value = true,
          Get.back(),
          fun(),
        },
      )
    );
  }

  Widget getContent(){
    return RichText(
      text: TextSpan(
        style: text_grey_12,
        children: [
          const TextSpan(text: '我已阅读并同意'),
          TextSpan(text: '《${Global.agreementUserTitle}》', style: text_main_12, recognizer: TapGestureRecognizer()..onTap = () {
            var map = {
              'title': Global.agreementUserTitle,
              'url': Global.getAgreementUser(),
            };
            Get.toNamed(Routes.H5_WEBVIEW, parameters: map);
          }),
          const TextSpan(text: '及'),
          TextSpan(text: '《${Global.agreementPolicyTitle}》', style: text_main_12, recognizer: TapGestureRecognizer()..onTap = (){
            var map = {
              'title': Global.agreementPolicyTitle,
              'url': Global.getAgreementPolicy(),
            };
            Get.toNamed(Routes.H5_WEBVIEW, parameters: map);
          }),
          const TextSpan(text: '\n未注册的手机号验证后自动创建用户'),
        ],
      ),
    );
  }


  /// 开发设置，例如代理
  HomeController homeController = Get.put(HomeController());
  void toDevSetting(){
    homeController.toDevSetting();
  }
}
